package com.ls.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.ls.common.config.AlipayConfig;
import com.ls.common.entity.AlipayBean;
import com.ls.order.mapper.OrderMapper;
import com.ls.order.pojo.entity.Order;
import com.ls.order.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author konglz
 * @Data 2023/3/7 11:44
 */
@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    AlipayConfig alipayConfig;



    @Autowired
    OrderMapper orderMapper;


    @Override
    public String preCreate(Integer id, Integer userId) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),alipayConfig.getApp_id(),alipayConfig.getPrivate_key(),alipayConfig.getFormat(),
                alipayConfig.getCharset(),alipayConfig.getPublic_key(),alipayConfig.getSign_type()
        );
        Order order = orderMapper.selectById(id);

        AlipayBean alipayBean = new AlipayBean();

        alipayBean.setOut_trade_no(order.getTradeOutNo());
        alipayBean.setSubject("商品订单");
        alipayBean.setTotal_amount(order.getPrice().toString());
        alipayBean.setBody("祝您生活愉快!");
        alipayBean.setUserId(userId);


        //扫码支付使用AlipayTradePrecreateRequest传参，下面调用的是execute方法
        AlipayTradePrecreateRequest precreateRequest = new AlipayTradePrecreateRequest();
        precreateRequest.setReturnUrl(alipayConfig.getReturn_url());
        precreateRequest.setNotifyUrl(alipayConfig.getNotify_url());
        precreateRequest.setBizContent(JSON.toJSONString(alipayBean));


        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(precreateRequest);
        } catch (AlipayApiException e) {
            System.out.println(e.getMessage());
            throw new Exception(String.format("下单失败 错误代码:[%s], 错误信息:[%s]", e.getErrCode(), e.getErrMsg()));
        }

        System.out.println(response.isSuccess());
        if (!response.isSuccess()) {
            throw new Exception(String.format("下单失败 错误代码:[%s], 错误信息:[%s]", response.getCode(), response.getMsg()));
        }
        System.out.println("============================tradeno=====================");
        System.out.println(response.getOutTradeNo());
        // 返回结果，主要是返回 qr_code，前端根据 qr_code 进行重定向或者生成二维码引导用户支付
//        JSONObject jsonObject = new JSONObject();
        //支付宝响应的订单号
//        String outTradeNo = response.getOutTradeNo();

//        jsonObject.put("outTradeNo",outTradeNo);
        //二维码地址，页面使用二维码工具显示出来就可以了
//        jsonObject.put("qrCode",response.getQrCode());
        return response.getQrCode();
    }

    @Override
    public boolean query(String id) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),alipayConfig.getApp_id(),alipayConfig.getPrivate_key(),alipayConfig.getFormat(),
                alipayConfig.getCharset(),alipayConfig.getPublic_key(),alipayConfig.getSign_type()
        );
        //查询订单的信息，有买家的名字、订单号、金额等等
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        //bizContent.put("trade_no", "2014112611001004680073956707");
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);

        if(response.isSuccess()){
            return true;
        } else {
            return false;
        }
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("userName", response.getBuyerUserName());
//        jsonObject.put("outTradeNo", response.getOutTradeNo());
//        jsonObject.put("price", response.getBuyerPayAmount());
    }

    @Override
    public boolean cancel(Order order) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),alipayConfig.getApp_id(),alipayConfig.getPrivate_key(),alipayConfig.getFormat(),
                alipayConfig.getCharset(),alipayConfig.getPublic_key(),alipayConfig.getSign_type()
        );
        AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", order.getTradeOutNo());
        request.setBizContent(bizContent.toString());
        AlipayTradeCancelResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean refund(Order order) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(
                alipayConfig.getGatewayUrl(),alipayConfig.getApp_id(),alipayConfig.getPrivate_key(),alipayConfig.getFormat(),
                alipayConfig.getCharset(),alipayConfig.getPublic_key(),alipayConfig.getSign_type()
        );
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", order.getTradeOutNo());
        bizContent.put("refund_amount", order.getPrice());
        bizContent.put("out_request_no", "HZ01RF001");

        //// 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return true;
        } else {
            return false;
        }
    }

















//    @Autowired
//    AlipayConfig alipayConfig;
//    @Override
//    public String toAlipay(AlipayBean alipayBean) {
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                alipayConfig.getGatewayUrl(),//支付宝网关
//                alipayConfig.getApp_id(),//appid
//                alipayConfig.getMerchant_private_key(),//商户私钥
//                alipayConfig.getFormate(),
//                alipayConfig.getCharset(),//字符编码格式
//                alipayConfig.getAlipay_public_key(),//支付宝公钥
//                alipayConfig.getSign_type());//签名方式
//        //2、设置请求参数
//        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//        //页面跳转同步通知页面路径
//        alipayRequest.setReturnUrl(alipayConfig.getReturn_url());
//        // 服务器异步通知页面路径
//        alipayRequest.setNotifyUrl(alipayConfig.getNotify_url());
//        //封装参数
//        alipayRequest.setBizContent(JSON.toJSONString(alipayBean));
//        String result="";
//        try {
//            //3、请求支付宝进行付款，并获取支付结果
//            result  = alipayClient.pageExecute(alipayRequest).getBody();
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//        //返回付款信息
//        return result;
//    }
}
